<template>
  <div class="background"></div>

  <nav-bar></nav-bar>

  <div class="container">
    <div class="searchBoxBackground">
      <!-- 不要删除这个container，用于空站位-->
      <el-container></el-container>

      <div class="header">

        <!--      搜索框列表展示-->
        <div v-for="(item, idx) in inputList"
             style="display:flex; flex-flow: row wrap; flex: 3 100%; justify-content: center; margin-left: 10%"
        >
          <div style="flex: 4;margin: 5px 10px;">
            <el-input
                v-model="item.content"
                placeholder="Please input"
                class="input-with-select"
                @keyup.enter="confirmInput"
            >

              <!--            字段选择框-->
              <template #prepend>
                <el-select v-model="item.select" placeholder="Select"
                           style="width: 90px;">
                  <el-option label="DOI" value="doi"></el-option>
                  <el-option label="篇名" value="title"></el-option>
                  <el-option label="来源" value="source"></el-option>
                  <el-option label="领域" value="fields"></el-option>
                  <el-option label="作者" value="author"></el-option>
                  <el-option label="机构" value="affiliation"></el-option>
<!--                  <el-option label="年份" value="year"></el-option>-->
                </el-select>
              </template>

              <!--            逻辑选择框-->
              <template #append>
                <el-select v-model="item.relation" placeholder="Select"
                           style="width: 90px;">
                  <el-option label="AND" value="must"></el-option>
                  <el-option label="OR" value="should"></el-option>
                  <el-option label="NOT" value="must_not"></el-option>
                </el-select>
              </template>
            </el-input>
          </div>

          <!--        精确或者模糊搜索-->
          <div style="flex: 0;margin: 5px 10px; order: -1;">
            <el-select class="selectOpts" v-model="item.kind" placeholder="模糊" style="width: 80px">
              <el-option label="模糊" value="match"></el-option>
              <el-option label="精确" value="match_phrase"></el-option>
            </el-select>
          </div>

          <!--        增加和删除按钮-->
          <div style="flex: 0.5 80px; margin: 8px 10px 5px; justify-content: right; align-items: center">
            <el-button class="condNumCtrlBtn" type="primary" size="mini" @click="addInputList(idx)"><el-icon><Plus></Plus></el-icon></el-button>
            <el-button class="condNumCtrlBtn" type="primary" size="mini" @click="delInputList(idx)" v-show="idx !== 0"><el-icon><Minus></Minus></el-icon></el-button>
          </div>
        </div>

        <el-divider></el-divider>
        <!--     确认和重置按钮 -->
        <div style="flex: 1 100%; display: flex; justify-content: center">
          <el-button type="primary" size="medium" @click="confirmInput">确认</el-button>
          <el-button size="medium" @click="selectResult">结果中筛选</el-button>
          <el-button size="medium" @click="resetInputList">重置</el-button>

        </div>

      </div>
      <!-- 不要删除这个container，用于空站位-->
      <el-container></el-container>
    </div>

    <!--            侧边栏筛选条目-->
    <div class="paperSearchMainContent">
      <div class="aside">

        <div class="asideMenu">
          <div  v-for="item in selectList">
            <div class="select-field">
              <div class="select-title">
                {{item.title}}
              </div>
              <div class="select-button">
                <el-popover placement="right"
                            :width="maxLength(item.list)"
                            trigger="click"
                            v-show="!item.loading"
                            @show="modifySelectList(item.name)">
                  <template #reference>
                    <el-button type="primary" size="mini">>></el-button>
                  </template>

                  <div class="filter-list">
                    <div class="filter-item" v-for="filter in item.list" v-if="!item.loading && item.list.length">
                      <el-checkbox :label="filter.content + '(' + filter.number + ')'" v-model="filter.chosen"
                                   @change="chooseFilter(filter.chosen, item.name, filter.content)">
                      </el-checkbox>
                    </div>
                    <div style="flex: 0 0 100px;" v-else-if="item.loading" v-loading="item.loading"></div>
                    <div style="flex: 0 0 100px; display: flex; justify-content: center; align-items: center; font-size: 16px"
                         v-else>NO DATA</div>
                  </div>
                </el-popover>
              </div>
            </div>
<!--            <Hr class="myDivider"/>-->
          </div>

        </div>

        <div class="buttons" style="display: flex;justify-content: center">
          <el-button type="primary" size="medium" @click="addDataFilter">确认</el-button>
          <el-button size="medium" @click="resetFilterList">重置</el-button>
        </div>

      </div>

      <div class="main">
        <!--      表格展示-->
        <el-table :data="resultList" stripe ref="multipleTable"
                  @sort-change="sortChange"
                  v-loading="loading"
                  element-loading-text="Loading..."
                  max-height="800px"
                  @cell-click="clickCell"
                  min-height="300px"
        >
          <el-table-column label="题名" resizable min-width="200px">
            <template #default="scope">
              <a @click="clickDetail(scope.row.id)" v-if="!scope.row.highlight['title']">{{scope.row.title}}</a>
              <a @click="clickDetail(scope.row.id)" v-else v-html="scope.row.highlight['title']"></a>
            </template>
          </el-table-column>
          <el-table-column label="作者" resizable width="200px">
            <template #default="scope">
            <span v-for="(item, idx) in scope.row.authors">
              <a @click="clickAuthor(item.authorId)"
                 v-if="!scope.row.highlight['authors.author']
                 || !contain(scope.row.highlight['authors.author'], item.author)">{{item.author}}</a>
              <a @click="clickAuthor(item.authorId)"
                 v-else v-html="scope.row.highlight['authors.author']"></a>
              <span v-if="idx !== scope.row.authors.length - 1">;</span>
            </span>
            </template>
          </el-table-column>
          <el-table-column label="来源" resizable width="200px">
            <template #default="scope">
              <span v-if="!scope.row.highlight['source']">{{scope.row.source}}</span>
              <span v-else v-html="scope.row.highlight['source']"></span>
            </template>
          </el-table-column>

          <el-table-column prop="date" label="发表时间" sortable="custom" width="100px"/>
          <el-table-column prop="sited" label="被引" sortable="custom" width="100px"/>
          <!--        <el-table-column label="操作" width="100px"/>-->
        </el-table>
        <!--      分页选择-->
        <div style="display: flex; justify-content: center; margin-top: 5px;">
          <el-pagination layout="total, sizes, prev, pager, next, jumper"
                         style=""
                         :total="totalNumber"
                         :current-page="currentPage"
                         :page-size="pageSize"
                         :page-sizes="[5, 10, 15, 20]"
                         @current-change="changePage"
                         @prev-click="prevPage"
                         @next-click="nextPage"
                         @size-change="changePageSize"
          >
          </el-pagination>
        </div>
      </div>
    </div>

  </div>

</template>

<script>
import axios from "../../utils/MyAxios";
import IndexNavBar from "../../components/PublicNavBar";
import { Plus, Minus } from '@element-plus/icons'


export default {
  name: "paperSearch",
  components: {
    'nav-bar': IndexNavBar,
    Plus,
    Minus,
  },
  data() {
    return {
      showNumber: 0,
      includes: [],
      currentPage: 1,
      totalNumber: 0,
      pageSize: 10,
      loading: false,
      headerHeightNumber: 1,
      totalSelect: 5,
      map: {
        'fields': 0, 'source': 1, 'authors': 2, 'affiliations': 3, 'year': 4
      },
      filterList: [],
      searchList: [],
      inputList: [],
      selectList: [],
      resultList: [],
      activeSelect: [], // result是否被选中
      page: 1,
      data: {
        track_total_hits: "true",
        _source: {
          includes: [],
          excludes: []
        },
        query: {
          bool: {
            must: [],
            must_not: [],
            should: [],
            filter: {
              bool: {
                must: []
              }
            }
          }
        },
        from: 0,
        size: 10,
        sort: [],
        aggs: {},
        highlight: {
          pre_tags: "<font color='red'>",
          post_tags: "</font>",
          fields: {}
        }
      }
    }
  },
  computed: {},
  methods: {
    confirmInput() {
      this.searchList.splice(0, this.searchList.length)
      for (let item of this.inputList) {
        let tmp = {}
        tmp.select = item.select
        tmp.content = item.content
        tmp.relation = item.relation
        tmp.kind = item.kind
        this.searchList.push(tmp)
      }
      this.confirmSearchList()
    },
    selectResult() {
      for (let item of this.inputList) {
        let tmp = {}
        tmp.select = item.select
        tmp.content = item.content
        tmp.relation = item.relation
        tmp.kind = item.kind
        this.searchList.push(tmp)
      }
      this.confirmSearchList()
    },
    resetInputList() {
      this.searchList.splice(0, this.searchList.length)
      this.inputList.splice(0, this.inputList.length)
      this.inputList.push({
        select: 'title',
        content: '',
        relation: 'must',
        kind: 'match_phrase'
      })
    },
    addInputList(idx) {
      this.inputList.splice(idx + 1, 0, {
        select: 'title',
        content: '',
        relation: 'must',
        kind: 'match_phrase'
      })
    },
    delInputList(idx) {
      this.inputList.splice(idx, 1)
    },
    maxLength(list){
      let result = 0;
      for (let i of list) {
        let j = i.content;
        result = result > j.length ? result : j.length
      }
        return result * 7 + 80
    },
    contain(str, pattern) {
      let list = pattern.split(/ +/)
      let result = false
      for (let i of list)
        for (let j of str)
         result |= j.search(i) !== -1
      return result
    },
    resetSelectList() {
      this.activeSelect.splice(0, this.activeSelect.length)
      this.selectList.splice(0, this.selectList.length)
      this.selectList.push(
          {
            title: "领域",
            name: "fields",
            show: false,
            loading: false,
            list: []
          },
          {
            title: "文献来源",
            name: "source",
            show: false,
            loading: false,
            list: []
          },
          {
            title: "作者",
            name: "authors",
            show: false,
            loading: false,
            list: []
          },
          {
            title: "机构",
            name: "affiliations",
            show: false,
            loading: false,
            list: []
          },
          {
            title: '年份',
            name: "year",
            show: false,
            loading: false,
            list: []
          })
    },
    resetDataFilter() {
      let now = this.data.query.bool.filter.bool.must
      now.splice(0, now.length)
      for (let i = 0; i < this.totalSelect; i++)
        now.push(
            {
              bool: {
                should: []
              }
            }
        )
    },
    resetFilterList() {
      this.filterList.splice(0, this.filterList.length)
    },
    addDataFilter() {
      let now = this.data.query.bool.filter.bool.must
      this.resetDataFilter()

      for (let item of this.filterList) {
        let group = this.map[item.select]
        let aim = {}, front = aim
        let select = item.select
        if (item.select === 'authors' || item.select === 'affiliations') {
          let author = {}
          author.nested = {}
          author.nested.path = 'authors'
          author.nested.query = {}
          aim = author
          front = author.nested.query
          select = "authors." + item.select.slice(0, item.select.length - 1)
        }
        front['match_phrase'] = {}
        front['match_phrase'][select] = item.content

        if (select === 'authors.author' || select === 'source')
          this.data.highlight.fields[select] = {}
        now[group].bool.should.push(aim)
      }
      this.resetSelectList()
      this.askForData()
    },
    chooseFilter(value, field, content) {
      let item = {
        select: field,
        content: content
      }
      if (value)
        this.filterList.push(item)
      else
        this.filterList.splice(this.filterList.findIndex(
            temp => item.select === temp.select && item.content === temp.content), 1)
      console.log(this.filterList)
    },
    sortChange(column) {
      let now = this.data.sort
      now.splice(0, now.length)
      let temp = {}
      let field = (column.prop === "date") ? "date" : "citationCount"
      let method = (column.order === "descending") ? "desc" : "asc"
      temp[field] = {}
      temp[field]['order'] = method
      now.push(temp)
      this.askForData()
    },
    confirmSearchList() {
      let now = this.data.query.bool
      now.must.splice(0, now.must.length)
      now.must_not.splice(0, now.must_not.length)
      now.should.splice(0, now.should.length)

      // now-> this.data.query.bool
      // aim-> 要push进list的对象
      // front-> 当前最深的对象
      this.data.highlight.fields = {}
      for (let item of this.searchList) {
        if (!item.content)
          continue;
        let aim = {}, front = aim
        let select = item.select
        if (item.select === 'author' || item.select === 'affiliation') {
          let author = {}
          author.nested = {}
          author.nested.path = 'authors'
          author.nested.query = {}
          aim = author
          front = author.nested.query
          select = "authors." + item.select
        }
        front[item.kind] = {}
        front[item.kind][select] = item.content

        // 文本高亮处理
        if (select === 'authors.author' || select === 'title' || select === 'source')
          this.data.highlight.fields[select] = {}
        now[item.relation].push(aim)
      }
      this.askForData()
    },
    askForData() {
      console.log(JSON.stringify(this.data))
      this.loading = true
      axios.post("http://121.36.3.252:9200/paper_new/_search", this.data).then(res => {
        console.log(res);
        this.addResultList(res.data.hits.hits)
        this.totalNumber = res.data.hits.total.value
        this.loading = false;
      })
      // let list = ["fields", "source", "authors", "affiliations", "year"]
      // for (let i of list)
      //   this.modifySelectList(i)
    },
    addResultList(data) {
      this.resultList.splice(0, this.resultList.length)
      for (let i of data) {
        let item = i._source
        // let authors = ""
        // for (let j of item.authors)
        //   authors += j.author + ";"
        // authors = authors.slice(0, authors.length - 1)
        this.resultList.push({
          id: item.id,
          title: item.title,
          authors: item.authors,
          source: item.source,
          date: item.date.slice(0, 10),
          sited: item.citationCount,
          highlight: i.highlight
        })
      }
    },
    modifySelectList(name) {
      console.log(name);
      if (this.activeSelect.indexOf(name) !== -1)
        return;
      this.activeSelect.push(name)

      let selector
      for (selector of this.selectList)
        if (selector.name === name)
          break;

      // if (selector.list.length !== 0)
      //   return

      let tmp = {}
      tmp["_group"] = {}
      tmp["_group"]["terms"] = {}
      if (selector.name !== 'year')
        tmp["_group"]["terms"]["field"] = selector.name + '_key'
      else
        tmp["_group"]["terms"]["field"] = selector.name
      this.data.aggs = tmp

      console.log(JSON.stringify(this.data));
      selector.loading = true;
      axios.post("http://121.36.3.252:9200/paper_new/_search", this.data).then(res => {
        console.log(res);
        for (let item of res.data.aggregations._group.buckets)
          selector.list.push({
            content: item['key'],
            chosen: this.filterList.findIndex(
                tmp => tmp.select === name && tmp.content === item['key']) !== -1,
            number: item['doc_count']
          })
        selector.loading = false
      })
    },
    changePage(newPage) {
      this.currentPage = newPage
      this.data.from = (this.currentPage - 1) * this.pageSize
      this.askForData()
    },
    prevPage() {
      this.data.from -= this.pageSize
      this.askForData()
    },
    nextPage() {
      this.data.from += this.pageSize
      this.askForData()
    },
    changePageSize(newPageSize) {
      this.pageSize = newPageSize
      this.data.size = this.pageSize
      this.askForData()
    },
    clickCell(row, column, cell, event) {
      console.log("row: ", row)
      console.log("column: ", column);
      console.log("cell: ", cell);
      console.log("event: ", event);
    },
    clickDetail(id) {
      const {href} = this.$router.resolve({
        path: '/detail',
        query: {
          paperId: id
        }
      })
      window.open(href, '_blank')
    },
    clickAuthor(id) {
      const { href } = this.$router.resolve({
        path: '/portal',
        query: {
          authorId: id
        }
      })
      window.open(href, '_blank')
    }
  },
  created() {
    console.log(this.$route.query)

    this.resetDataFilter()

    this.inputList.push({
      select: 'title',
      content: this.$route.query.key,
      relation: 'must',
      kind: 'match_phrase'
    })

    this.includes = ["id", "title", "authors", "source", "date", "citationCount"]
    this.data._source.includes = this.includes
    this.resetSelectList()
    if (this.$route.query.key)
      this.confirmInput()



  }
}

</script>
}

<style scoped>

.select-fields {
  display: flex;
  flex-flow: column wrap;
  background-color: #0066ff00;
}

.select-field {
  flex: 1;
  /*border: 4px solid #e4e4e4;*/

  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
  align-items: center;
  margin: 10px 0;
  background-color: #ffffff80;
  padding: 10px;
  /*margin-bottom: 20px;*/
}

.select-title {
  color: rgb(68, 68, 68);
  font-family: serif;
  font-size: large;
  font-weight: bold;
  margin-left: 2%;
}

.selectOpts ::v-deep{
  --el-select-border-color-hover: black;
}

.asideMenu {
  /*background: linear-gradient( #b9c9e1, #edecdf);*/
}

.myDivider {
  height: 2px;
  background-color: white;
  border-color: white;
}

.select-button {
  display: flex;
  flex-flow: row wrap;

}

.filter-list {
  display: flex;
  flex-flow: column wrap;
}

.filter-item {
  flex: 1;
  margin: 1px 0px;
}

.container {
  /*margin: 0px 10%;*/
  /*display: flex;*/
  /*flex-flow: row wrap;*/
}

.searchBoxBackground {
  background-image: url("../../index/assets/indexBackground.jpg");
}

.background {
  background-image: url("../../index/assets/indexBackground.jpg");
  background-size: 100% 100%;
  width: 100%;
  height: 100%;
  z-index: -1;
  position: fixed;
  bottom: 0;
  opacity: 0.5;
}

.header {
  flex: 1 100%;
  display: flex;
  flex-flow: row wrap;
  align-items: center;
  margin: 3% 10% 1%;
  /*border: 1px solid #e4e4e4;*/
  /*box-shadow: 0 5px 5px #cdcdcd;*/

}

.paperSearchMainContent {
  display: flex;
}

.aside {
  margin-left: 5%;
  margin-top: 0.5%;
  /*margin: 30px 0px;*/
  flex: 1 auto;
}

.condNumCtrlBtn ::v-deep {
  margin-left: 2%;
  --el-button-border-color: rgb(66,130,209);
  --el-button-background-color: rgb(66,130,209);

}

.select-item {
  margin-bottom: 15px;

  border: 1px solid #ebebeb;
  box-shadow: 0 2px 3px 0 rgb(210 210 210 / 75%);
}

.main {
  /*margin: 30px 10px;*/
  margin-left: 1%;
  margin-right: 5%;
  flex: 7 0;
  padding: 10px;
  border: 1px solid #e4e4e4;
  box-shadow: 0 5px 5px #cdcdcd;
}


.main a:hover{
  color: dodgerblue;
  cursor: pointer;
}

* {
  font-family: "Times New Roman", Serif;

}

</style>